<template>
	<view class="edit-profile-page">
		<!-- 表单 -->
		<up-form ref="formRef" :model="formData" :rules="rules">
			<!-- 头像 -->
			<up-form-item label="头像">
				<view class="avatar-upload" @click="handleChooseAvatar">
					<up-image :src="formData.avatar" width="100rpx" height="100rpx" shape="circle"></up-image>
					<view class="upload-hint">
						<up-icon name="camera-fill" size="16" color="#36d399"></up-icon>
						<text>更换头像</text>
					</view>
				</view>
			</up-form-item>

			<!-- 昵称 -->
			<up-form-item label="昵称" prop="nickname" required>
				<up-input v-model="formData.nickname" placeholder="请输入昵称" border="none"
					:clearable="true"></up-input>
			</up-form-item>

			<!-- 性别 -->
			<up-form-item label="性别" prop="gender" required>
				<view class="gender-selector" @click="showGenderSelector = true">
					<text class="gender-text" v-if="formData.gender">{{ getGenderText(formData.gender) }}</text>
					<text class="gender-placeholder" v-else>请选择性别</text>
					<up-icon name="arrow-down" size="16"></up-icon>
				</view>
			</up-form-item>

			<!-- 生日 -->
			<up-form-item label="生日">
				<view class="date-selector" @click="showDatePicker = true">
					<text class="date-text" v-if="formData.birthday">{{ formData.birthday }}</text>
					<text class="date-placeholder" v-else>请选择生日</text>
					<up-icon name="arrow-down" size="16"></up-icon>
				</view>
			</up-form-item>

			<!-- 学院 -->
			<up-form-item label="学院" prop="college" required>
				<up-input v-model="formData.college" placeholder="请输入所在学院" border="none"
					:clearable="true"></up-input>
			</up-form-item>

			<!-- 专业 -->
			<up-form-item label="专业" prop="major" required>
				<up-input v-model="formData.major" placeholder="请输入专业" border="none" :clearable="true"></up-input>
			</up-form-item>

			<!-- 手机号 -->
			<up-form-item label="手机号" prop="phoneNumber">
				<up-input v-model="formData.phoneNumber" type="number" placeholder="请输入手机号" border="none"
					:clearable="true"></up-input>
			</up-form-item>

			<!-- 个人简介 -->
			<up-form-item label="个人简介">
				<up-textarea v-model="formData.introduction" placeholder="介绍一下自己吧..." :maxlength="200"
					:count="true" height="150rpx"></up-textarea>
			</up-form-item>
		</up-form>

		<!-- 保存按钮 -->
		<view class="save-section">
			<up-button type="primary" @click="handleSave" :loading="saving" color="#36d399" class="save-btn">
				保存
			</up-button>
		</view>

		<!-- 性别选择器 -->
		<up-popup v-model:show="showGenderSelector" mode="bottom" round="20">
			<view class="selector-popup">
				<view class="popup-header">
					<text class="popup-title">选择性别</text>
					<up-icon name="close" size="20" @click="showGenderSelector = false"></up-icon>
				</view>
				<view class="selector-list">
					<view class="selector-option" v-for="option in genderOptions" :key="option.value"
						:class="{ active: formData.gender === option.value }" @click="handleSelectGender(option)">
						<text class="option-text">{{ option.label }}</text>
						<up-icon name="checkmark" size="20" color="#36d399"
							v-if="formData.gender === option.value"></up-icon>
					</view>
				</view>
			</view>
		</up-popup>

		<!-- 日期选择器 -->
		<up-datetime-picker v-model:show="showDatePicker" v-model="birthdayTimestamp" mode="date"
			@confirm="handleDateConfirm" @cancel="showDatePicker = false">
		</up-datetime-picker>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		computed,
		onMounted
	} from 'vue';
	import {
		updateUserService
	} from '../../server/api/user.js';
	import showToast from '../../utils/showToast.js';
	import {
		adaptUserInfo
	} from '../../utils/dataAdapter.js';

	// 状态
	const formRef = ref(null);
	const saving = ref(false);
	const showGenderSelector = ref(false);
	const showDatePicker = ref(false);

	// 性别选项
	const genderOptions = [{
			value: 1,
			label: '男'
		},
		{
			value: 2,
			label: '女'
		},
		{
			value: 0,
			label: '保密'
		}
	];

	// 表单数据
	const formData = reactive({
		userId: null,
		avatar: '',
		nickname: '',
		gender: null,
		birthday: '',
		college: '',
		major: '',
		phoneNumber: '',
		introduction: ''
	});

	// 生日时间戳
	const birthdayTimestamp = ref(Date.now());

	// 表单验证规则
	const rules = {
		nickname: [{
				required: true,
				message: '请输入昵称',
				trigger: ['blur', 'change']
			},
			{
				min: 2,
				max: 20,
				message: '昵称长度在2-20位之间',
				trigger: ['blur', 'change']
			}
		],
		gender: [{
			required: true,
			message: '请选择性别',
			trigger: ['change']
		}],
		college: [{
			required: true,
			message: '请输入所在学院',
			trigger: ['blur', 'change']
		}],
		major: [{
			required: true,
			message: '请输入专业',
			trigger: ['blur', 'change']
		}],
		phoneNumber: [{
			pattern: /^1[3-9]\d{9}$/,
			message: '请输入正确的手机号',
			trigger: ['blur', 'change']
		}]
	};

	/**
	 * 加载用户信息
	 */
	const loadUserInfo = () => {
		const userInfo = uni.getStorageSync('userInfo');

		if (userInfo) {
			formData.userId = userInfo.userId;
			formData.avatar = userInfo.avatar || 'https://picsum.photos/200/200?random=999';
			formData.nickname = userInfo.nickname || '';
			formData.gender = userInfo.gender || null;
			formData.birthday = userInfo.birthday || '';
			formData.college = userInfo.college || '';
			formData.major = userInfo.major || '';
			formData.phoneNumber = userInfo.phoneNumber || '';
			formData.introduction = userInfo.introduction || '';

			// 设置生日时间戳
			if (formData.birthday) {
				birthdayTimestamp.value = new Date(formData.birthday).getTime();
			}
		}
	};

	/**
	 * 获取性别文本
	 */
	const getGenderText = (value) => {
		const option = genderOptions.find(opt => opt.value === value);
		return option ? option.label : '';
	};

	/**
	 * 选择性别
	 */
	const handleSelectGender = (option) => {
		formData.gender = option.value;
		showGenderSelector.value = false;
	};

	/**
	 * 确认日期
	 */
	const handleDateConfirm = (value) => {
		const date = new Date(value);
		formData.birthday = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
		showDatePicker.value = false;
	};

	/**
	 * 选择头像
	 */
	const handleChooseAvatar = () => {
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			success: (res) => {
				const tempFilePath = res.tempFilePaths[0];

				// 这里应该上传到服务器，暂时使用本地路径
				formData.avatar = tempFilePath;
				showToast('头像已选择，保存后生效', 'success');
			},
			fail: (err) => {
				console.error('选择头像失败:', err);
				showToast('选择头像失败', 'error');
			}
		});
	};

	/**
	 * 保存资料
	 */
	const handleSave = async () => {
		// 表单验证
		try {
			await formRef.value.validate();
		} catch (errors) {
			console.log('表单验证失败:', errors);
			return;
		}

		saving.value = true;

		try {
			// 准备提交数据 - 后端需要nickName字段（大写N）
			const submitData = {
				nickName: formData.nickname,  // 转换为后端字段名
				avatar: formData.avatar,
				Introduction: formData.introduction,  // 转换为后端字段名
				phoneNumber: formData.phoneNumber,
				gender: formData.gender,
				birthday: formData.birthday
			};
			
			// 调用真实API
			const res = await updateUserService(submitData);

			if (res.code === 200) {
				// 更新本地存储
				const userInfo = uni.getStorageSync('userInfo');
				const updatedUserInfo = {
					...userInfo,
					...formData
				};
				uni.setStorageSync('userInfo', updatedUserInfo);

				showToast('保存成功', 'success');

				// 延迟返回
				setTimeout(() => {
					uni.navigateBack();
				}, 1000);
			} else {
				showToast(res.message || '保存失败', 'error');
			}
		} catch (error) {
			console.error('保存资料异常:', error);
			showToast(error.message || '网络错误，请稍后重试', 'error');
		} finally {
			saving.value = false;
		}
	};

	// 页面加载
	onMounted(() => {
		loadUserInfo();
	});
</script>

<style lang="scss" scoped>
	.edit-profile-page {
		min-height: 100vh;
		background-color: #f5f5f5;
		padding-bottom: 180rpx;

		/* #ifdef H5 */
		:deep(.u-form) {
			background-color: #ffffff;
		}

		:deep(.u-form-item__body__left__content__label) {
			font-size: 28rpx;
			font-weight: 500;
		}

		:deep(.u-form-item) {
			padding: 30rpx;
		}
		/* #endif */
		
		/* #ifndef H5 */
		// 小程序端使用全局样式覆盖
		.u-form {
			background-color: #ffffff !important;
		}

		.u-form-item__body__left__content__label {
			font-size: 28rpx !important;
			font-weight: 500 !important;
		}

		.u-form-item {
			padding: 30rpx !important;
		}
		/* #endif */
	}

	// 头像上传
	.avatar-upload {
		display: flex;
		align-items: center;
		gap: 20rpx;

		.upload-hint {
			display: flex;
			align-items: center;
			gap: 8rpx;
			font-size: 26rpx;
			color: #36d399;
		}
	}

	// 性别选择器
	.gender-selector,
	.date-selector {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 0;

		.gender-text,
		.date-text {
			font-size: 28rpx;
			color: #333333;
		}

		.gender-placeholder,
		.date-placeholder {
			font-size: 28rpx;
			color: #cccccc;
		}
	}

	// 保存按钮
	.save-section {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #ffffff;
		padding: 20rpx 30rpx;
		box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.05);
		z-index: 100;

		.save-btn {
			width: 100%;
			height: 80rpx;
			font-size: 32rpx;
			font-weight: bold;
		}
	}

	// 选择器弹窗
	.selector-popup {
		background-color: #ffffff;
		border-radius: 20rpx 20rpx 0 0;

		.popup-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 30rpx;
			border-bottom: 1rpx solid #f5f5f5;

			.popup-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333333;
			}
		}

		.selector-list {
			.selector-option {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 40rpx 30rpx;
				border-bottom: 1rpx solid #f5f5f5;
				transition: background-color 0.3s;

				&.active {
					background-color: #f0fdf4;
				}

				.option-text {
					font-size: 28rpx;
					color: #333333;
				}
			}
		}
	}
</style>

